package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    //根据ID删除分类，删除前判断，不关联其他表数据才进行删除操作
    @Override
    public void remove(Long id) {
        //如果关联了菜品或者套餐，则抛出业务异常，通过全局异常处理器进行异常处理
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, id);
        //关联菜品的条数
        int count = dishService.count(queryWrapper);

        LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Setmeal::getCategoryId, id);
        //管理套餐的数量
        int count1 = setmealService.count(queryWrapper1);
        //没有关联的数据,进行删除
        if (count == 0 && count1 == 0) {
            super.removeById(id);
        } else {
            throw new CustomException("当前分类下关联了菜品或者套餐，不能删除");
        }
    }
}